package com.cz.run.web;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cz.run.beans.base.PageDTO;
import com.cz.run.beans.base.ReturnDTO;
import com.cz.run.beans.mysql.*;
import com.cz.run.beans.po.pocket.AddPO;
import com.cz.run.beans.po.pocket.ExtractPO;
import com.cz.run.beans.po.pocket.TransferPO;
import com.cz.run.beans.vo.extract.Extract;
import com.cz.run.beans.vo.pocket.PocketLogVO;
import com.cz.run.beans.vo.pocket.PocketVO;
import com.cz.run.constants.ConstantKey;
import com.cz.run.service.*;
import com.cz.run.utils.DateUtil;
import com.cz.run.utils.MD5;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;


/**
 * <p>
 * 口袋表 前端控制器
 * </p>
 *
 * @author CAIYJ
 * @since 2018-06-02
 */
@RestController
@RequestMapping("/userPocket")
public class UserPocketServer {

    @Autowired
    private IUserPocketService iUserPocketService;

    @Autowired
    private IUserBaseService iUserBaseService;

    @Autowired
    private IUserIdentityAuthService iUserIdentityAuthService;

    @Autowired
    private IUserPocketLogService iUserPocketLogService;

    @Autowired
    private IUserPointService iUserPointService;

    @Autowired
    private IUserPocketPointLogService iUserPocketPointLogService;


    @ApiOperation(value = "口袋信息", notes = "口袋信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/getPocket")
    public ReturnDTO<PocketVO> getPocket(@RequestBody PageDTO po, HttpServletRequest request) throws Exception {
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        if (StringUtils.isEmpty(userId)) {
            return ReturnDTO.fail("userId不能为空");
        }

        EntityWrapper<UserIdentityAuth> userEw = new EntityWrapper<>();
        userEw.where("user_id = {0}", userId);
        UserIdentityAuth userIdentityAuth = iUserIdentityAuthService.selectOne(userEw);

        PocketVO pocketVO = new PocketVO();

        if (null == userIdentityAuth) {
            pocketVO.setStat(0);
            return ReturnDTO.success(pocketVO);
        }

        EntityWrapper<UserPocket> pocketEw = new EntityWrapper<>();
        pocketEw.where("user_id={0}", userId);
        UserPocket userPocket1 = iUserPocketService.selectOne(pocketEw);

        if (null == userPocket1) {
            pocketVO.setStat(1);
            return ReturnDTO.success(pocketVO);
        }

        Page<UserPocketLog> page = new Page<>(po.getCurrentPage(), po.getPageSize());
        EntityWrapper<UserPocketLog> ew = new EntityWrapper<>();
        ew.where(!StringUtils.isEmpty(userPocket1.getAddress()), "address = {0}", userPocket1.getAddress());

        page = iUserPocketLogService.selectPage(page, ew);
        if (page != null && page.getRecords() != null && page.getRecords().size() > 0) {
            List<PocketLogVO> list = new ArrayList<>();
            PocketLogVO vo = null;
            for (UserPocketLog userPocketLog : page.getRecords()) {
                vo = new PocketLogVO();
                BeanUtils.copyProperties(vo, userPocketLog);
                if (null != userPocketLog.getCreateTime()) {
                    vo.setTime(DateUtil.currentTimeMillisCN1(userPocketLog.getCreateTime()));
                }
                list.add(vo);
            }
            po.setContent(list);
        }
        po.setTotalRecord(page.getTotal());

        pocketVO.setPo(po);
        pocketVO.setAddress(userPocket1.getAddress());
        pocketVO.setShc(userPocket1.getShc());

        return ReturnDTO.success(pocketVO);

    }

    @ApiOperation(value = "创建口袋", notes = "创建口袋", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/add")
    public ReturnDTO<String> add(@RequestBody AddPO po, HttpServletRequest request) throws Exception {
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        if (StringUtils.isEmpty(po.getPassword())) {
            return ReturnDTO.fail("口袋密码不能为空");
        }

        EntityWrapper<UserBase> userEw = new EntityWrapper<>();
        userEw.where("id = {0}", userId);
        UserBase userBase = iUserBaseService.selectOne(userEw);
        if(null!=userBase&&0==userBase.getStatus()){
            return ReturnDTO.fail("账户被封禁，请联系客服");
        }
        if (null == userBase) {
            return ReturnDTO.fail("用户不存在");
        }

        EntityWrapper<UserPocket> ew = new EntityWrapper<>();
        ew.where("user_id={0}", userId);
        UserPocket userPocket1 = iUserPocketService.selectOne(ew);
        if (null != userPocket1) {
            return ReturnDTO.fail("用户已存在");
        }

        UserPocket userPocket = new UserPocket();
        userPocket.setUserId(Integer.parseInt(userId));
        userPocket.setPassword(MD5.GetMD5Code(po.getPassword()));
        userPocket.setAddress(genRandomNum());
        userPocket.setCreateTime(new Date());
        userPocket.setUpdateTime(new Date());
        userPocket.setShc(new Double(0));

        iUserPocketService.insert(userPocket);

        return ReturnDTO.success("创建成功");

    }

    @ApiOperation(value = "转账", notes = "转账", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/transfer")
    public ReturnDTO<String> transfer(@RequestBody TransferPO po, HttpServletRequest request) throws Exception {
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);

        if (StringUtils.isEmpty(po.getPassword())) {
            return ReturnDTO.fail("密码不能为空");
        }

        if (StringUtils.isEmpty(po.getAddress())) {
            return ReturnDTO.fail("转账地址不能为空");
        }

        if (po.getShc() == 0) {
            return ReturnDTO.fail("转账个数不能为0");
        }

        EntityWrapper<UserBase> userEw = new EntityWrapper<>();
        userEw.where("id = {0}", userId);
        UserBase userBase = iUserBaseService.selectOne(userEw);
        if(null!=userBase&&0==userBase.getStatus()){
            return ReturnDTO.fail("账户被封禁，请联系客服");
        }
        if (null == userBase) {
            return ReturnDTO.fail("用户不存在");
        }

        EntityWrapper<UserPocket> zew = new EntityWrapper<>();
        zew.where("address={0}", po.getAddress());
        UserPocket zuserPocket = iUserPocketService.selectOne(zew);
        if (null == zuserPocket) {
            return ReturnDTO.fail("转账对象不存在");
        }

        EntityWrapper<UserPocket> ew = new EntityWrapper<>();
        ew.where("user_id={0}", userId);
        UserPocket userPocket1 = iUserPocketService.selectOne(ew);

        if (null == userPocket1) {
            return ReturnDTO.fail("用户不存在");
        }

        if (!userPocket1.getPassword().equals(MD5.GetMD5Code(po.getPassword()))) {
            return ReturnDTO.fail("密码错误");
        }

        if (po.getShc() > userPocket1.getShc()) {
            return ReturnDTO.fail("超出余额");
        }

        userPocket1.setShc(userPocket1.getShc() - po.getShc());
        iUserPocketService.updateById(userPocket1);

        zuserPocket.setShc(zuserPocket.getShc() + po.getShc());
        iUserPocketService.updateById(zuserPocket);

        EntityWrapper<UserPocket> aew = new EntityWrapper<>();
        aew.where("user_id={0}", 0);
        UserPocket allUserPock = iUserPocketService.selectOne(aew);

        allUserPock.setShc(allUserPock.getShc() + po.getShc());
        allUserPock.setUpdateTime(new Date());
        iUserPocketService.updateById(allUserPock);

        UserPocketLog userPocketLog = new UserPocketLog();
        userPocketLog.setAddress(zuserPocket.getAddress());
        userPocketLog.setAmount(Double.parseDouble(String.valueOf(po.getShc())));
        userPocketLog.setCreateTime(new Date());
        userPocketLog.setUpdateTime(new Date());
        userPocketLog.setFrom(userPocket1.getAddress());
        userPocketLog.setType("0");
        iUserPocketLogService.insert(userPocketLog);

        userPocketLog.setAddress(userPocket1.getAddress());
        userPocketLog.setFrom(zuserPocket.getAddress());
        userPocketLog.setType("1");
        iUserPocketLogService.insert(userPocketLog);

        return ReturnDTO.success("转账成功");

    }

    @ApiOperation(value = "提取/兑换", notes = "提取/兑换", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/extract")
    public ReturnDTO<Extract> extract(@RequestBody ExtractPO po, HttpServletRequest request) throws Exception {
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        if (StringUtils.isEmpty(userId)) {
            return ReturnDTO.fail("用户未登录");
        }

        if (po.getType().equals("1")&&StringUtils.isEmpty(po.getPassword())) {
            return ReturnDTO.fail("密码不能为空");
        }

        if (StringUtils.isEmpty(po.getType())) {
            return ReturnDTO.fail("类型不能为空");
        }

        if ("1".equals(po.getType())&&(null == po.getNum() || po.getNum() == 0)) {
            return ReturnDTO.fail("个数不能为0");
        }

        Extract extract = new Extract();

        EntityWrapper<UserBase> userEw = new EntityWrapper<>();
        userEw.where("id = {0}", userId);
        UserBase userBase = iUserBaseService.selectOne(userEw);
        if(null!=userBase&&0==userBase.getStatus()){
            return ReturnDTO.fail("账户被封禁，请联系客服");
        }

        if (null == userBase) {
            return ReturnDTO.fail("用户不存在");
        }


        EntityWrapper<UserPocket> ew = new EntityWrapper<>();
        ew.where("user_id={0}", userId);
        UserPocket userPocket1 = iUserPocketService.selectOne(ew);
        if (null == userPocket1) {
            extract.setType(0);
            return ReturnDTO.success(extract);
        }

        EntityWrapper<UserPoint> pointEw = new EntityWrapper<>();
        pointEw.where("user_id={0}", userId);
        UserPoint userPoint = iUserPointService.selectOne(pointEw);

        if (null == userPoint) {
            return ReturnDTO.fail("用户不存在");
        }

        if (po.getType().equals("1")&&!MD5.GetMD5Code(po.getPassword()).equals(userPocket1.getPassword())) {
            return ReturnDTO.fail("密码错误");
        }

        UserPocketPointLog userPocketPointLog = new UserPocketPointLog();
        userPocketPointLog.setUserId(Integer.parseInt(userId));
        userPocketPointLog.setCreateTime(new Date());
        userPocketPointLog.setUpdateTime(new Date());


        if ("0".equals(po.getType())) {
            if (userPoint.getPoint() <= 0.1) {
                return ReturnDTO.fail("余额小于提取手续费");
            }

            userPocket1.setShc(userPocket1.getShc() + userPoint.getPoint() - 0.1);
            userPoint.setPoint(new Double(0));

            userPocketPointLog.setType("0");
            userPocketPointLog.setPoint(userPoint.getPoint());

        } else if ("1".equals(po.getType())) {
            if (userPocket1.getShc() < po.getNum()) {
                return ReturnDTO.fail("余额小于兑换额度");
            }

            if (userPocket1.getShc() <= 0.1) {
                return ReturnDTO.fail("余额小于兑换手续费");
            }

            userPoint.setPoint(userPoint.getPoint() + po.getNum() - 0.1);
            userPocket1.setShc(userPocket1.getShc() - po.getNum());
            userPocketPointLog.setType("1");
            userPocketPointLog.setPoint(Double.parseDouble(String.valueOf(po.getNum())));
        }

        iUserPocketPointLogService.insert(userPocketPointLog);
        iUserPointService.updateById(userPoint);
        iUserPocketService.updateById(userPocket1);
        extract.setType(1);
        return ReturnDTO.success(extract);

    }

    /**
     * 字符串转化成为16进制字符串
     *
     * @param s
     * @return
     */
    public static String strTo16(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return "0x" + str;
    }

    public static String genRandomNum(){
        int  maxNum = 36;
        int i;
        int count = 0;
        char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
                'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while(count < 40){
            i = Math.abs(r.nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count ++;
            }
        }
        return "0x" +pwd.toString();
    }

    public static  void main(String[] args){
        System.out.print(genRandomNum());
    }
}